/**
  * Copyright 2008 Ling Hu
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  **/

var Surfacelate = {'version': '0.0.1dev'};

Surfacelate.Translater = (function() {

  var uniqueInstance;

  function reduceSpace(s) {
    return s.replace(/\n\t*/g,' ').replace(/^\s*(.*?)\s*$/, "$1"); //remove space char both sides and replace \n\t.
  }

  function transDom(oLang, element){  //the oLang object must like this format: oLang = { 'from_string1' : 'to_string1',......,'from_stringN' : 'to_stringN' }
    var i;

    if(element.childNodes.length <= 0) {
      var nodeText;
      if(element.nodeName == "#text" && (nodeText = reduceSpace(element.data)).length > 1 ) {
        if(oLang[nodeText]) element.data = oLang[nodeText];
      } else if(element.nodeName == "INPUT" && (element.type == "submit" || element.type == "button")) {
        nodeText = reduceSpace(element.value);
        if(oLang[nodeText]) element.value = oLang[nodeText];
      }
    } else {
      for(i=0; i < element.childNodes.length; i++) {
        transDom(oLang, element.childNodes.item(i));
      }
    }
  }

  function constructor() {
    return{

      translate: function(oLang, element){
        if(!element) element = document;
        transDom(oLang, element);
      }

    }
  }

  return {
    getInstance: function() {
      if(!uniqueInstance) { // Instantiate only if the instance doesn't exist.
        uniqueInstance = constructor();
      }
      return uniqueInstance;
    }
  }
})();

var ST = Surfacelate.Translater.getInstance();
